package ru.nlezhnev.services.request_processor;

import java.sql.SQLException;

import ru.nlezhnev.utils.ASObjectUtils;
import ru.nlezhnev.utils.FarmRequest;
import ru.nlezhnev.utils.StackTraceUtil;
import flex.messaging.io.amf.ASObject;

abstract public class FarmRequestProcessor {
	private ASObject requestResult;
	protected int uid;
	protected ASObject data;
	
	public FarmRequestProcessor(byte[] inputData, String vid, String methodName) {
		try {
			FarmRequest request = new FarmRequest(inputData, vid);
			if (request.isCheckFailed()) {
				requestResult = getFailResponse("Invalid vid", methodName);
			} else {
				uid = request.getUid();
				data = request.getData();
				ASObjectUtils.replaceNativeArrays(data);
				
				requestResult = getOKResponse(performRequest(), methodName);
			}
		} catch (Exception e) {			
			requestResult = getFailResponse(StackTraceUtil.getStackTrace(e), methodName);
		}
	}
	
	public ASObject getResult() {
		return requestResult;
	}
	
	abstract protected Object performRequest() throws SQLException;
	
	@SuppressWarnings("unchecked")
	protected ASObject prepareResponseData(ASObject value) {
		ASObjectUtils.replaceAsObjectsToArrays(value);
		ASObject result = new ASObject();
		result.put("data", value);
		return result;
	}
	
	@SuppressWarnings("unchecked")
	private ASObject getResponse(Object message, String methodName) {
		ASObject response = new ASObject();
		response.put("response", message);
		response.put("method", methodName);
		return response;
	}
	
//	@SuppressWarnings("unchecked")
	protected ASObject getOKResponse(Object message, String methodName) {
		return getResponse(message, methodName);
	}
	
	@SuppressWarnings("unchecked")
	private ASObject getFailResponse(String error, String methodName) {
		ASObject response = new ASObject();
		response.put("error_msg", error);
		return getResponse(response, methodName);
	}
}
